package cloud

import (
	"dgo/MyProj/PrjHttpUtils"
	"dgo/goutils/utils"
	"dgo/goutils/yhttp"
	"dgo/plg/plgnet"
	"fmt"
	"gitee.com/ymofen/gobase/golog"
	"gitee.com/ymofen/supervalue"
	"net/http"
	"net/url"
)

type transferVxItem struct {
	data string
}

/*
*

	地址需要在【公众号设置】的【功能设置】【网页授权域名】进行授权

step1->redirect(vx-serv)->uri(step2)?param
*/
func (this *PlgVxApi) onHttpVxGetOpenIDStep1(w http.ResponseWriter, r *http.Request) {
	PrjHttpUtils.AllowCrossAccessSet(w)
	uri := r.URL.Query().Get("uri")
	param := r.URL.Query().Get("param")
	if len(param) == 0 {
		param = this.openid_code_redirect_param
	}
	transfer := r.URL.Query().Encode()

	uuid := utils.RandKeyString(24)
	if len(param) > 0 {
		param += "&"
	}
	//param += fmt.Sprint("uuid=%s&transfer=%s", uuid, utils.QueryUrlBase64AndEncode([]byte(transfer)))
	param += fmt.Sprintf("uuid=%s", uuid)
	this.transferMap.Set(uuid, &transferVxItem{data: transfer})

	if len(uri) > 0 {
		u0 := this.VxUtil.GetURL4Code(uri, param)
		this.LogInfoMessage("VxGetOpenIDStep1, [%s]transfer:%s   重定向:%s", uuid, transfer, u0)
		http.Redirect(w, r, u0, http.StatusTemporaryRedirect)
	} else {
		u0 := this.VxUtil.GetURL4Code(this.openid_code_redirect_uri, param)
		this.LogInfoMessage("VxGetOpenIDStep1, [%s]transfer:%s   重定向:%s", uuid, transfer, u0)
		http.Redirect(w, r, u0, http.StatusTemporaryRedirect)
	}
}

func (this *PlgVxApi) onHttpVxGetOpenIDStep2(w http.ResponseWriter, r *http.Request) {
	PrjHttpUtils.AllowCrossAccessSet(w)
	req := plgnet.NewPlgHttpRec(w, r)
	code := req.QryAsString("code", "")
	if len(code) == 0 {
		golog.Warnf("前端缺少code参数!")
	}
	json, err := this.VxUtil.GetOpenIDByCode(code)
	if json == nil {
		json.SetKeyValue("err", err.Error())
	}

	statestr := req.QryAsString("state", "")
	if len(statestr) > 0 {
		// 不一定需要
		qry, _ := url.ParseQuery(statestr)
		uuid := qry.Get("uuid")
		if len(uuid) > 0 {
			obj := this.transferMap.Get(uuid, nil)
			if obj != nil {
				itm := obj.(*transferVxItem)
				json.SetKeyValue("transfer", itm.data)
				this.LogInfoMessage("VxGetOpenIDStep2 get, [%s]transfer:%s", uuid, itm.data)
			} else {
				this.LogInfoMessage("VxGetOpenIDStep2 get, [%s]transfer:找不到对于的对象", uuid)
			}
		} else {
			this.LogInfoMessage("VxGetOpenIDStep2 get, uuid is empty")
		}
	} else {
		this.LogInfoMessage("VxGetOpenIDStep2 get, state 参数为空")
	}

	var sb utils.BytesBuilder

	sb.Appendf("[%s]请求参数\n", req.ClientAddr())
	sb.Appendf("url:%s\n", req.ReqR.URL.String())
	PrjHttpUtils.GetRequestHeader(req.ReqR.Header, ":", "\n", &sb)
	sb.Appendf("\n")
	sb.Write(req.BodyBuf)
	sb.Appendf("\n")
	if err != nil {
		sb.Appendf("openid err:%s\n", err.Error())
	}
	if json != nil {
		sb.Appendf("openid resp:%s\n", json.AsJSONString(false))
	}

	json.SetKeyValue("id", this.PlugId)

	this.LogInfoMessage("VxGetOpenIDStep2:%s", sb.String())

	if len(this.on_getopenid_action_uri) > 0 {
		url0 := this.on_getopenid_action_uri
		p := this.on_getopenid_action_param
		if len(p) > 0 {
			url0 += "?" + p
		}

		respBuf, err := yhttp.DefaultHttpPostString(url0, "application/json", json.AsJSONString(false))
		if err != nil {
			http.Error(w, err.Error(), 503)
		} else {
			this.LogInfoMessage("VxGetOpenIDStep2, 访问:%s, 响应:%s", url0, string(respBuf))
			json1, err := wrapper.NewSVFromBuf(respBuf)
			if err != nil {
				http.Error(w, fmt.Sprintf("解析(%s)响应出现异常:%s", this.on_getopenid_action_uri, err.Error()), 503)
			} else {
				str := json1.StringByName("redirect-url", "")
				if len(str) > 0 {
					http.Redirect(w, r, str, json1.IntByName("redirect-url-code", http.StatusTemporaryRedirect))
				}
				return
			}
		}
	} else {
		w.Write(sb.Bytes())
	}
}

func (this *PlgVxApi) onHttpVxGetOpenIDStep2_Test(w http.ResponseWriter, r *http.Request) {
	PrjHttpUtils.AllowCrossAccessSet(w)
	req := plgnet.NewPlgHttpRec(w, r)
	req.CheckDecodeBody()
	var sb utils.BytesBuilder

	sb.Appendf("[%s]请求参数\n", req.ClientAddr())
	sb.Appendf("url:%s\n", req.ReqR.URL.String())
	PrjHttpUtils.GetRequestHeader(req.ReqR.Header, ":", "\n", &sb)
	sb.Appendf("\n")
	sb.Write(req.BodyBuf)
	sb.Appendf("\n")

	/**
	  {
	    "access_token":"54_S56u-k8dBbrFiX549zYwExQkTMs6QzM5gOuH3F71cL3i8qJ8nL5k-0hu3cK8odnIImc3OemrG9-QRFXO3NDr_4Ny-5CXjqdTcnbL-BWvuWU",
	    "expires_in":7200,
	    "refresh_token":"54_ElMpaymR-Wt2gB1KaA5fqpwgFBJDLPF6l7BnEmpWx1_Vgw5waBn7loWVPQn06Uc208ckG5aLdltp-rDtepXnLK24qbjhJhJz_-km1nrcXOk",
	    "openid":"o2224jsjUZmNeFTqcC1WwGAPWzao",
	    "scope":"snsapi_userinfo",
	    "__url":"https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxcabe9d879ff40cdd&secret=1864531c2ac47ab796f55c897ddcdca8&code=041EbE000Qc8oN1Rm1300s3AWL3EbE0y&grant_type=authorization_code",
	    "transfer":"userid=170"
	  }
	*/
	utils.Log.Debugf(sb.String())

	req.ResponseJSONValues("redirect-url", "https://gps.xktms.com/vxbind/result.html?userid=170980")
}
